import React, { useState, useContext, createContext } from 'react';
import { ArrowLeft, ChevronRight, Home, BarChart3 } from 'lucide-react';

// 导航上下文
const NavigationContext = createContext();

// 导航提供者
export const NavigationProvider = ({ children }) => {
  const [navigationHistory, setNavigationHistory] = useState([]);
  const [currentContext, setCurrentContext] = useState(null);
  
  // 添加导航记录
  const pushNavigation = (module, section, context = {}) => {
    const newEntry = {
      module,
      section,
      context,
      timestamp: Date.now()
    };
    setNavigationHistory(prev => [...prev, newEntry]);
    setCurrentContext(context);
  };

  // 返回上一级
  const goBack = () => {
    if (navigationHistory.length > 1) {
      const newHistory = navigationHistory.slice(0, -1);
      setNavigationHistory(newHistory);
      const lastEntry = newHistory[newHistory.length - 1];
      setCurrentContext(lastEntry?.context || null);
      return lastEntry;
    }
    return null;
  };

  // 跳转到特定模块
  const navigateToModule = (module, section = null, context = {}) => {
    pushNavigation(module, section, context);
  };

  // 获取面包屑导航
  const getBreadcrumbs = () => {
    return navigationHistory.map((entry, index) => ({
      ...entry,
      isLast: index === navigationHistory.length - 1
    }));
  };

  const value = {
    navigationHistory,
    currentContext,
    pushNavigation,
    goBack,
    navigateToModule,
    getBreadcrumbs
  };

  return (
    <NavigationContext.Provider value={value}>
      {children}
    </NavigationContext.Provider>
  );
};

// 使用导航的Hook
export const useNavigation = () => {
  const context = useContext(NavigationContext);
  if (!context) {
    throw new Error('useNavigation must be used within a NavigationProvider');
  }
  return context;
};

// 面包屑组件
export const Breadcrumbs = ({ className = '' }) => {
  const { getBreadcrumbs, goBack, navigateToModule } = useNavigation();
  const breadcrumbs = getBreadcrumbs();

  if (breadcrumbs.length === 0) return null;

  return (
    <nav className={`flex items-center space-x-2 text-sm ${className}`}>
      <button
        onClick={() => navigateToModule('home')}
        className="flex items-center text-gray-500 hover:text-gray-700"
      >
        <Home className="h-4 w-4" />
      </button>
      
      {breadcrumbs.map((crumb, index) => (
        <React.Fragment key={index}>
          <ChevronRight className="h-4 w-4 text-gray-400" />
          <button
            onClick={() => {
              if (!crumb.isLast && index < breadcrumbs.length - 1) {
                // 跳转到历史记录中的某一级
                navigateToModule(crumb.module, crumb.section, crumb.context);
              }
            }}
            className={`${
              crumb.isLast 
                ? 'text-gray-900 font-medium' 
                : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            {crumb.module}
            {crumb.section && ` - ${crumb.section}`}
          </button>
        </React.Fragment>
      ))}
    </nav>
  );
};

// 统一的页面头部组件
export const UnifiedPageHeader = ({ 
  title, 
  subtitle, 
  icon: Icon, 
  actions = [], 
  showBreadcrumbs = true,
  onBack = null 
}) => {
  const { goBack } = useNavigation();

  const handleBack = () => {
    if (onBack) {
      onBack();
    } else {
      goBack();
    }
  };

  return (
    <header className="bg-white border-b border-gray-200 px-6 py-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          {(onBack || goBack) && (
            <button
              onClick={handleBack}
              className="flex items-center text-gray-500 hover:text-gray-700 transition-colors group"
            >
              <ArrowLeft className="h-4 w-4 mr-1 group-hover:-translate-x-0.5 transition-transform" />
              <span className="text-sm font-medium">返回</span>
            </button>
          )}
          
          <div className="flex items-center space-x-3">
            {Icon && (
              <div className="p-2 bg-blue-100 rounded-lg">
                <Icon className="h-5 w-5 text-blue-600" />
              </div>
            )}
            <div>
              <h1 className="text-xl font-bold text-gray-900">{title}</h1>
              {subtitle && (
                <p className="text-sm text-gray-500">{subtitle}</p>
              )}
            </div>
          </div>
        </div>

        {actions.length > 0 && (
          <div className="flex items-center space-x-3">
            {actions.map((action, index) => (
              <button
                key={index}
                onClick={action.onClick}
                className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                  action.variant === 'primary' 
                    ? 'bg-blue-600 text-white hover:bg-blue-700'
                    : 'border border-gray-300 text-gray-700 hover:bg-gray-50'
                }`}
              >
                {action.icon && <action.icon className="h-4 w-4 mr-2" />}
                {action.label}
              </button>
            ))}
          </div>
        )}
      </div>

      {showBreadcrumbs && (
        <div className="mt-3">
          <Breadcrumbs />
        </div>
      )}
    </header>
  );
};

// 模块间跳转链接组件
export const ModuleLink = ({ 
  module, 
  section = null, 
  context = {}, 
  children, 
  className = '',
  onClick = null 
}) => {
  const { navigateToModule } = useNavigation();

  const handleClick = (e) => {
    e.preventDefault();
    if (onClick) {
      onClick();
    }
    navigateToModule(module, section, context);
  };

  return (
    <button onClick={handleClick} className={className}>
      {children}
    </button>
  );
};

// 跨模块数据传递Hook
export const useCrossModuleData = () => {
  const { currentContext } = useNavigation();
  
  const getContextData = (key) => {
    return currentContext?.[key] || null;
  };

  const hasContextData = (key) => {
    return currentContext && currentContext.hasOwnProperty(key);
  };

  return {
    currentContext,
    getContextData,
    hasContextData
  };
}; 